/*
 * Accelerometer.cpp
 *
 *  Created on: 2011. 3. 15.
 *      Author: JeeHoon
 */
#include "plugin/Accelerometer.h"

#include "api/PluginManager.h"
#include "api/PluginResult.h"

using namespace Osp::Base;

Accelerometer::Accelerometer()
{
	__pSensorManager = NULL;
	__hasListener = false;
}

Accelerometer::~Accelerometer()
{
	if(NULL != __pSensorManager)
	{
		delete __pSensorManager;
	}
}

result
Accelerometer::OnConstruct(PluginManager * pPluginManager, Osp::Base::String pluginName)
{
	result r = E_SUCCESS;

	if(NULL == __pSensorManager)
	{
		__pSensorManager = new Osp::Uix::SensorManager();
		__pSensorManager->Construct();
		__pSensorManager->GetMinInterval(Osp::Uix::SENSOR_TYPE_ACCELERATION,__minInterval);
		__pSensorManager->GetMaxInterval(Osp::Uix::SENSOR_TYPE_ACCELERATION,__maxInterval);
	}

	return r;
}

result
Accelerometer::execute(Osp::Base::String action, Osp::Base::String args, Osp::Base::String callbackId)
{
	result r = E_SUCCESS;

	if(action == L"start")
	{
		long int interval = 1000;

		String value = getJSONObjectItem(args,L"frequency");
		if(value != L"") Long::Parse(value,interval);

		r = start(interval);
	}
	else if(action == L"stop")
	{
		r = stop();
	}
	else
	{
		printLog(L"Unknown action: " + action );
	}

	return r;
}

/*
 *	NATIVE CODE
 */

result
Accelerometer::start(long int interval)
{
	result r = E_SUCCESS;
	__interval = interval;
	interval = (interval > __maxInterval ? __maxInterval : interval);
	interval = (interval < __minInterval ? __minInterval : interval);

	if( false == __hasListener )
	{
		r = __pSensorManager->AddSensorListener(*this,Osp::Uix::SENSOR_TYPE_ACCELERATION,interval,false);
		__hasListener = true;
	}

	return r;
}

result
Accelerometer::stop()
{
	result r = E_SUCCESS;

	if(true == __hasListener)
	{
		r = __pSensorManager->RemoveSensorListener(*this,Osp::Uix::SENSOR_TYPE_ACCELERATION);
		__hasListener = false;
	}

	return r;
}

void
Accelerometer::OnDataReceived(Osp::Uix::SensorType sensorType, Osp::Uix::SensorData &sensorData, result r)
{
	static long int past = 0;
	static long int now = 0;

	sensorData.GetValue((Osp::Uix::SensorDataKey)Osp::Uix::ACCELERATION_DATA_KEY_TIMESTAMP,now);

	if( (now - past) >= __interval )
	{
		float x,y,z;
		sensorData.GetValue((Osp::Uix::SensorDataKey)Osp::Uix::ACCELERATION_DATA_KEY_X,x);
		sensorData.GetValue((Osp::Uix::SensorDataKey)Osp::Uix::ACCELERATION_DATA_KEY_Y,y);
		sensorData.GetValue((Osp::Uix::SensorDataKey)Osp::Uix::ACCELERATION_DATA_KEY_Z,z);

		String code;
		code.Format(1024,L"navigator.accelerometer._onAccelUpdate(%f,%f,%f);",x,y,z);
		__pPluginManager->evaluateJavascript(code);
		past = now;
	}
}

